<!DOCTYPE html>
<html>
  <head><meta name="generator" content="Hexo 3.8.0">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="fengzhaoyang&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
  <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
    java8 Lambda Stream collect Collectors 常用详细实例 | fzy-blog
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/css/style.css">
  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
  <script src="/js/qrious.js"></script>
  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.png">
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>fzy-blog</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">Tags</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">Archives</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/project/" class="item-link">Projects</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">About</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">Tags</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">Archives</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/project/" class="menu-link">Projects</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">About</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>java8 Lambda Stream collect Collectors 常用详细实例</h2>
  <p class="post-date">2019-05-24</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="java8-Lambda-Stream-collect-Collectors-常用详细实例"><a href="#java8-Lambda-Stream-collect-Collectors-常用详细实例" class="headerlink" title="java8 Lambda Stream collect Collectors 常用详细实例"></a>java8 Lambda Stream collect Collectors 常用详细实例</h1><p>优雅的将一个对象的集合转化成另一个对象的集合</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List&lt;OrderDetail&gt; orderDetailList = orderDetailService.listOrderDetails();</span><br><span class="line">List&lt;CartDTO&gt; cartDTOList = orderDetailList.stream()</span><br><span class="line">                .map(e -&gt; <span class="keyword">new</span> CartDTO(e.getProductId(), e.getProductQuantity()))</span><br><span class="line">                .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>
<p>交集 (list1 + list2)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">List&lt;T&gt; intersect = list1.stream()</span><br><span class="line">                         .filter(list2::contains)</span><br><span class="line">                         .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>
<p>差集</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//(list1 - list2)</span></span><br><span class="line">List&lt;String&gt; reduce1 = list1.stream().filter(item -&gt; !list2.contains(item)).collect(toList());</span><br><span class="line"></span><br><span class="line"><span class="comment">//(list2 - list1)</span></span><br><span class="line">List&lt;String&gt; reduce2 = list2.stream().filter(item -&gt; !list1.contains(item)).collect(toList());</span><br></pre></td></tr></table></figure>
<p>并集</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用并行流</span></span><br><span class="line">List&lt;String&gt; listAll = list1.parallelStream().collect(toList());</span><br><span class="line">List&lt;String&gt; listAll2 = list2.parallelStream().collect(toList());</span><br><span class="line">listAll.addAll(listAll2);</span><br></pre></td></tr></table></figure>
<p>去重并集</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; listAllDistinct = listAll.stream()</span><br><span class="line">.distinct().collect(toList());</span><br></pre></td></tr></table></figure>
<p>从 List 中过滤出一个元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">User match = users.stream()</span><br><span class="line">.filter((user) -&gt; user.getId() == <span class="number">1</span>).findAny().get();</span><br></pre></td></tr></table></figure>
<p>Map 集合转 List</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Person&gt; list = map.entrySet().stream().sorted(Comparator.comparing(e -&gt; e.getKey()))</span><br><span class="line">		.map(e -&gt; <span class="keyword">new</span> Person(e.getKey(), e.getValue())).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">List&lt;Person&gt; list = map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).map(e -&gt; <span class="keyword">new</span> Person(e.getKey(), e.getValue())).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">List&lt;Person&gt; list = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(e -&gt; <span class="keyword">new</span> Person(e.getKey(), e.getValue())).collect(Collectors.toList());</span><br></pre></td></tr></table></figure>
<p>Collectors toList</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">streamArr.collect(Collectors.toList());</span><br><span class="line">List&lt;Integer&gt; collectList = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">        .collect(Collectors.toList());</span><br><span class="line">System.out.println(<span class="string">"collectList: "</span> + collectList);</span><br><span class="line"><span class="comment">// 打印结果 collectList: [1, 2, 3, 4]</span></span><br></pre></td></tr></table></figure>
<p>Collectors toMap</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">map value 为对象 student</span><br><span class="line">Map&lt;Integer, Student&gt; map = list.stream().collect(Collectors.toMap(Student::getId, student -&gt; student));</span><br><span class="line"><span class="comment">// 遍历打印结果</span></span><br><span class="line">map.forEach((key, value) -&gt; &#123;</span><br><span class="line">    System.out.println(<span class="string">"key: "</span> + key + <span class="string">"    value: "</span> + value);</span><br><span class="line">&#125;);</span><br><span class="line">map value 为对象中的属性</span><br><span class="line">Map&lt;Integer, String&gt; map = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));</span><br><span class="line">map.forEach((key, value) -&gt; &#123;</span><br><span class="line">    System.out.println(<span class="string">"key: "</span> + key + <span class="string">"    value: "</span> + value);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>List 集合转 Map</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*使用Collectors.toMap形式*/</span></span><br><span class="line">Map result = peopleList.stream().collect(Collectors.toMap(p -&gt; p.name, p -&gt; p.age, (k1, k2) -&gt; k1));</span><br><span class="line"><span class="comment">//其中Collectors.toMap方法的第三个参数为键值重复处理策略，如果不传入第三个参数，当有相同的键时，会抛出一个IlleageStateException。</span></span><br><span class="line"><span class="comment">//或者</span></span><br><span class="line">Map&lt;Integer, String&gt; result1 = list.stream().collect(Collectors.toMap(Hosting::getId, Hosting::getName));</span><br><span class="line"><span class="comment">//List&lt;People&gt; -&gt; Map&lt;String,Object&gt;</span></span><br><span class="line">List&lt;People&gt; peopleList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">peopleList.add(<span class="keyword">new</span> People(<span class="string">"test1"</span>, <span class="string">"111"</span>));</span><br><span class="line">peopleList.add(<span class="keyword">new</span> People(<span class="string">"test2"</span>, <span class="string">"222"</span>));</span><br><span class="line">Map result = peopleList.stream().collect(HashMap::<span class="keyword">new</span>,(map,p)-&gt;map.put(p.name,p.age),Map::putAll);</span><br></pre></td></tr></table></figure>
<p>List<apple> 转 Map&lt;Integer,Apple&gt;</apple></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * List&lt;Apple&gt; -&gt; Map&lt;Integer,Apple&gt;</span></span><br><span class="line"><span class="comment"> * 需要注意的是：</span></span><br><span class="line"><span class="comment"> * toMap 如果集合对象有重复的key，会报错Duplicate key ....</span></span><br><span class="line"><span class="comment"> *  apple1,apple12的id都为1。</span></span><br><span class="line"><span class="comment"> *  可以用 (k1,k2)-&gt;k1 来设置，如果有重复的key,则保留key1,舍弃key2</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Map&lt;Integer, Apple&gt; appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -&gt; a,(k1, k2) -&gt; k1));</span><br></pre></td></tr></table></figure>
<p>List<people> 转 List&lt;Map&lt;String,Object&gt;&gt;</people></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Map&lt;String,Object&gt;&gt; personToMap = peopleList.stream().map((p) -&gt; &#123;</span><br><span class="line">    Map&lt;String, Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    map.put(<span class="string">"name"</span>, p.name);</span><br><span class="line">    map.put(<span class="string">"age"</span>, p.age);</span><br><span class="line">    <span class="keyword">return</span> map;</span><br><span class="line">&#125;).collect(Collectors.toList());</span><br><span class="line"><span class="comment">//或者</span></span><br><span class="line">List&lt;Map&lt;String,Object&gt;&gt; personToMap = peopleList.stream().collect(ArrayList::<span class="keyword">new</span>, (list, p) -&gt; &#123;</span><br><span class="line">   Map&lt;String, Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    map.put(<span class="string">"name"</span>, p.name);</span><br><span class="line">    map.put(<span class="string">"age"</span>, p.age);</span><br><span class="line">    list.add(map);</span><br><span class="line">&#125;, List::addAll);</span><br></pre></td></tr></table></figure>
<p>字典查询和数据转换 toMap 时，如果 value 为 null,会报空指针异常<br>解决办法一：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;String, List&lt;Dict&gt;&gt; resultMaps = Arrays.stream(dictTypes)</span><br><span class="line">.collect(Collectors.toMap(i -&gt; i, i -&gt; Optional.ofNullable(dictMap.get(i)).orElse(<span class="keyword">new</span> ArrayList&lt;&gt;()), (k1, k2) -&gt; k2));</span><br></pre></td></tr></table></figure>
<p>解决办法二：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;String, List&lt;Dict&gt;&gt; resultMaps = Arrays.stream(dictTypes)</span><br><span class="line">.filter(i -&gt; dictMap.get(i) != <span class="keyword">null</span>).collect(Collectors.toMap(i -&gt; i, dictMap::get, (k1, k2) -&gt; k2));</span><br></pre></td></tr></table></figure>
<p>解决办法三：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;String, String&gt; memberMap = list.stream().collect(HashMap::<span class="keyword">new</span>, (m,v)-&gt;</span><br><span class="line">    m.put(v.getId(), v.getImgPath()),HashMap::putAll);</span><br><span class="line">System.out.println(memberMap);</span><br></pre></td></tr></table></figure>
<p>解决办法四：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;String, String&gt; memberMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">list.forEach((answer) -&gt; memberMap.put(answer.getId(), answer.getImgPath()));</span><br><span class="line">System.out.println(memberMap);</span><br><span class="line"></span><br><span class="line">Map&lt;String, String&gt; memberMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"><span class="keyword">for</span> (Member member : list) &#123;</span><br><span class="line">    memberMap.put(member.getId(), member.getImgPath());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>假设有一个 User 实体类，有方法 getId(),getName(),getAge()等方法，现在想要将 User 类型的流收集到一个 Map 中，示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;User&gt; userStream = Stream.of(<span class="keyword">new</span> User(<span class="number">0</span>, <span class="string">"张三"</span>, <span class="number">18</span>), <span class="keyword">new</span> User(<span class="number">1</span>, <span class="string">"张四"</span>, <span class="number">19</span>), <span class="keyword">new</span> User(<span class="number">2</span>, <span class="string">"张五"</span>, <span class="number">19</span>), <span class="keyword">new</span> User(<span class="number">3</span>, <span class="string">"老张"</span>, <span class="number">50</span>));</span><br><span class="line"></span><br><span class="line">Map&lt;Integer, User&gt; userMap = userSteam.collect(Collectors.toMap(User::getId, item -&gt; item));</span><br></pre></td></tr></table></figure>
<p>假设要得到按年龄分组的 Map&lt;Integer,List<user>&gt;,可以按这样写：</user></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, List&lt;User&gt;&gt; ageMap = userStream.collect(Collectors.toMap(User::getAge, Collections::singletonList, (a, b) -&gt; &#123;</span><br><span class="line">            List&lt;User&gt; resultList = <span class="keyword">new</span> ArrayList&lt;&gt;(a);</span><br><span class="line">            resultList.addAll(b);</span><br><span class="line">            <span class="keyword">return</span> resultList;</span><br><span class="line">        &#125;));</span><br><span class="line"></span><br><span class="line">Map&lt;Integer, String&gt; map = persons</span><br><span class="line">    .stream()</span><br><span class="line">    .collect(Collectors.toMap(</span><br><span class="line">        p -&gt; p.age,</span><br><span class="line">        p -&gt; p.name,</span><br><span class="line">        (name1, name2) -&gt; name1 + <span class="string">";"</span> + name2));</span><br><span class="line"></span><br><span class="line">System.out.println(map);</span><br><span class="line"><span class="comment">// &#123;18=Max, 23=Peter;Pamela, 12=David&#125;</span></span><br></pre></td></tr></table></figure>
<p>List&lt;String&gt; 转 String</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//java8 String.join 方式</span></span><br><span class="line">List&lt;String&gt; webs = Arrays.asList(<span class="string">"voidcc.com"</span>, <span class="string">"voidmvn.com"</span>, <span class="string">"voidtool.com"</span>);</span><br><span class="line"><span class="comment">//webs 必须是List&lt;String&gt;</span></span><br><span class="line">String allwebs = String.join(<span class="string">","</span>, webs);</span><br><span class="line">System.out.println(allwebs);</span><br><span class="line"></span><br><span class="line"><span class="comment">//stream</span></span><br><span class="line">List&lt;String&gt; webs = Arrays.asList(<span class="string">"voidcc.com"</span>, <span class="string">"voidmvn.com"</span>, <span class="string">"voidtool.com"</span>);</span><br><span class="line">String allwebs = webs.stream().collect(Collectors.joining(<span class="string">","</span>));</span><br><span class="line">System.out.println(allwebs);</span><br></pre></td></tr></table></figure>
<p>Collectors toSet</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Set&lt;String&gt; result = Stream.of(<span class="string">"aa"</span>, <span class="string">"bb"</span>, <span class="string">"cc"</span>, <span class="string">"aa"</span>).collect(HashSet::<span class="keyword">new</span>, HashSet::add, HashSet::addAll);</span><br><span class="line"><span class="comment">//Collectors类中已经预定义好了toList，toSet，toMap，toCollection等方便使用的方法，所以以上代码还可以简化如下：</span></span><br><span class="line">Set&lt;String&gt; result2 = Stream.of(<span class="string">"aa"</span>, <span class="string">"bb"</span>, <span class="string">"cc"</span>, <span class="string">"aa"</span>).collect(Collectors.toSet());</span><br><span class="line"></span><br><span class="line">Set&lt;Integer&gt; collectSet = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>).collect(Collectors.toSet());</span><br><span class="line">System.out.println(<span class="string">"collectSet: "</span> + collectSet);</span><br><span class="line"><span class="comment">// 打印结果 collectSet: [1, 2, 3, 4]</span></span><br><span class="line"></span><br><span class="line">Stack stack1 = stream.collect(Collectors.toCollection(Stack::<span class="keyword">new</span>));</span><br><span class="line"><span class="comment">// collect toString</span></span><br><span class="line">String str = stream.collect(Collectors.joining()).toString();</span><br></pre></td></tr></table></figure>
<p>Collectors groupingBy</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, List&lt;User&gt;&gt; ageMap2 = userStream</span><br><span class="line">.collect(Collectors.groupingBy(User::getAge));</span><br></pre></td></tr></table></figure>
<p>groupingBy 分组后操作<br>//Collectors 中还提供了一些对分组后的元素进行 downStream 处理的方法：<br>//counting 方法返回所收集元素的总数；<br>//summing 方法会对元素求和；<br>//maxBy 和 minBy 会接受一个比较器，求最大值，最小值；<br>//mapping 函数会应用到 downstream 结果上，并需要和其他函数配合使用；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, Long&gt; sexCount = userStream.collect(Collectors.groupingBy(User::getSex,Collectors.counting()));</span><br><span class="line"></span><br><span class="line">Map&lt;Integer, Integer&gt; ageCount = userStream.collect(Collectors.groupingBy(User::getSex,Collectors.summingInt(User::getAge)));</span><br><span class="line"></span><br><span class="line">Map&lt;Integer, Optional&lt;User&gt;&gt; ageMax =  userStream.collect(Collectors.groupingBy(User::getSex,Collectors.maxBy(Comparator.comparing(User::getAge))));</span><br><span class="line"></span><br><span class="line">Map&lt;Integer, List&lt;String&gt;&gt; nameMap =  userStream.collect(Collectors.groupingBy(User::getSex,Collectors.mapping(User::getName,Collectors.toList())));</span><br></pre></td></tr></table></figure>
<p>groupingBy 根据年龄来分组：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, List&gt; peopleByAge = peoples.stream()</span><br><span class="line">.filter(p -&gt; p.age &gt; <span class="number">12</span>).collect(Collectors.groupingBy(p -&gt; p.age, Collectors.toList()));</span><br></pre></td></tr></table></figure>
<p>groupingBy 根据年龄分组，年龄对应的键值 List 存储的为 Person 的姓名:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, List&gt; peopleByAge = people.stream()</span><br><span class="line">.collect(Collectors.groupingBy(p -&gt; p.age, Collectors.mapping((Person p) -&gt; p.name, Collectors.toList())));</span><br><span class="line"><span class="comment">//mapping即为对各组进行投影操作，和Stream的map方法基本一致。</span></span><br></pre></td></tr></table></figure>
<p>groupingBy 根据姓名分组，获取每个姓名下人的年龄总和:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Map sumAgeByName = peoples.stream().collect(Collectors.groupingBy(p -&gt; p.name, Collectors.reducing(<span class="number">0</span>, (Person p) -&gt; p.age, Integer::sum)));</span><br><span class="line"><span class="comment">/* 或者使用summingInt方法 */</span></span><br><span class="line">sumAgeByName = peoples.stream().collect(Collectors.groupingBy(p -&gt; p.name, Collectors.summingInt((Person p) -&gt; p.age)));</span><br></pre></td></tr></table></figure>
<p>groupingBy Boolean 分组:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Boolean, List&lt;Integer&gt;&gt; collectGroup = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">            .collect(Collectors.groupingBy(it -&gt; it &gt; <span class="number">3</span>));</span><br><span class="line">System.out.println(<span class="string">"collectGroup : "</span> + collectGroup);</span><br><span class="line"><span class="comment">// 打印结果</span></span><br><span class="line"><span class="comment">// collectGroup : &#123;false=[1, 2, 3], true=[4]&#125;</span></span><br></pre></td></tr></table></figure>
<p>groupingBy 按年龄分组</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, List&lt;Person&gt;&gt; personsByAge = persons.stream().collect(Collectors.groupingBy(p -&gt; p.age));</span><br><span class="line">personsByAge.forEach((age, p) -&gt; System.out.format(<span class="string">"age %s: %s\n"</span>, age, p));</span><br><span class="line"><span class="comment">// age 18: [Max]</span></span><br><span class="line"><span class="comment">// age 23: [Peter, Pamela]</span></span><br><span class="line"><span class="comment">// age 12: [David]</span></span><br></pre></td></tr></table></figure>
<p>Collectors partitioningBy<br>Collectors 中还提供了 partitioningBy 方法，接受一个 Predicate 函数，该函数返回 boolean 值，用于将内容分为两组。假设 User 实体中包含性别信息 getSex()，可以按如下写法将 userStream 按性别分组：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Boolean, List&lt;User&gt;&gt; sexMap = userStream</span><br><span class="line">.collect(Collectors.partitioningBy(item -&gt; item.getSex() &gt; <span class="number">0</span>));</span><br></pre></td></tr></table></figure>
<p>可以看到 Java8 的分组功能相当强大，当然你还可以完成更复杂的功能。另外 Collectors 中还存在一个类似 groupingBy 的方法：partitioningBy，它们的区别是 partitioningBy 为键值为 Boolean 类型的 groupingBy，这种情况下它比 groupingBy 更有效率。<br>partitioningBy 将数字的 Stream 分解成奇数集合和偶数集合。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Boolean, List&lt;Integer&gt;&gt; collectParti = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">            .collect(Collectors.partitioningBy(it -&gt; it % <span class="number">2</span> == <span class="number">0</span>));</span><br><span class="line">System.out.println(<span class="string">"collectParti : "</span> + collectParti);</span><br><span class="line"><span class="comment">// 打印结果</span></span><br><span class="line"><span class="comment">// collectParti : &#123;false=[1, 3], true=[2, 4]&#125;</span></span><br></pre></td></tr></table></figure>
<p>Collectors joining<br>Collectors.joining 收集 Stream 中的值，该方法可以方便地将 Stream 得到一个字符串。joining 函数接受三个参数，分别表示允（用以分隔元素）、前缀和后缀:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">String names = peoples.stream().map(p-&gt;p.name).collect(Collectors.joining(<span class="string">","</span>))</span><br><span class="line"></span><br><span class="line">String strJoin = Stream.of(<span class="string">"1"</span>, <span class="string">"2"</span>, <span class="string">"3"</span>, <span class="string">"4"</span>)</span><br><span class="line">        .collect(Collectors.joining(<span class="string">","</span>, <span class="string">"["</span>, <span class="string">"]"</span>));</span><br><span class="line">System.out.println(<span class="string">"strJoin: "</span> + strJoin);</span><br><span class="line"><span class="comment">// 打印结果</span></span><br><span class="line"><span class="comment">// strJoin: [1,2,3,4]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//字符串连接</span></span><br><span class="line">String phrase = persons</span><br><span class="line">    .stream()</span><br><span class="line">    .filter(p -&gt; p.age &gt;= <span class="number">18</span>)</span><br><span class="line">    .map(p -&gt; p.name)</span><br><span class="line">    .collect(Collectors.joining(<span class="string">" and "</span>, <span class="string">"In Germany "</span>, <span class="string">" are of legal age."</span>));</span><br><span class="line">System.out.println(phrase);</span><br><span class="line"><span class="comment">// In Germany Max and Peter and Pamela are of legal age.</span></span><br></pre></td></tr></table></figure>
<p>组合 Collectors:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Boolean, Long&gt; partiCount = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">        .collect(Collectors.partitioningBy(it -&gt; it.intValue() % <span class="number">2</span> == <span class="number">0</span>,</span><br><span class="line">                Collectors.counting()));</span><br><span class="line">System.out.println(<span class="string">"partiCount: "</span> + partiCount);</span><br><span class="line"><span class="comment">// 打印结果</span></span><br><span class="line"><span class="comment">// partiCount: &#123;false=2, true=2&#125;</span></span><br></pre></td></tr></table></figure>
<p>Collectors 分别提供了求平均值 averaging、总数 couting、最小值 minBy、最大值 maxBy、求和 suming 等操作。但是假如你希望将流中结果聚合为一个总和、平均值、最大值、最小值，那么 Collectors.summarizing(Int/Long/Double)就是为你准备的，它可以一次行获取前面的所有结果，其返回值为(Int/Long/Double)SummaryStatistics。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">DoubleSummaryStatistics dss = people.collect(Collectors.summarizingDouble((Person p)-&gt;p.age));</span><br><span class="line"><span class="keyword">double</span> average=dss.getAverage();</span><br><span class="line"><span class="keyword">double</span> max=dss.getMax();</span><br><span class="line"><span class="keyword">double</span> min=dss.getMin();</span><br><span class="line"><span class="keyword">double</span> sum=dss.getSum();</span><br><span class="line"><span class="keyword">double</span> count=dss.getCount();</span><br><span class="line"></span><br><span class="line">IntSummaryStatistics ageSummary = persons</span><br><span class="line">        .stream()</span><br><span class="line">        .collect(Collectors.summarizingInt(p -&gt; p.age));</span><br><span class="line"></span><br><span class="line">System.out.println(ageSummary);</span><br><span class="line"><span class="comment">// IntSummaryStatistics&#123;count=4, sum=76, min=12, average=19.000000, max=23&#125;</span></span><br></pre></td></tr></table></figure>
<p>使用 collect 可以将 Stream 转换成值。maxBy 和 minBy 允许用户按照某个特定的顺序生成一个值。<br>averagingDouble:求平均值，Stream 的元素类型为 double<br>averagingInt:求平均值，Stream 的元素类型为 int<br>averagingLong:求平均值，Stream 的元素类型为 long<br>counting:Stream 的元素个数<br>maxBy:在指定条件下的，Stream 的最大元素<br>minBy:在指定条件下的，Stream 的最小元素<br>reducing: reduce 操作<br>summarizingDouble:统计 Stream 的数据(double)状态，其中包括 count，min，max，sum 和平均。<br>summarizingInt:统计 Stream 的数据(int)状态，其中包括 count，min，max，sum 和平均。<br>summarizingLong:统计 Stream 的数据(long)状态，其中包括 count，min，max，sum 和平均。<br>summingDouble:求和，Stream 的元素类型为 double<br>summingInt:求和，Stream 的元素类型为 int<br>summingLong:求和，Stream 的元素类型为 long</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;Integer&gt; collectMaxBy = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">            .collect(Collectors.maxBy(Comparator.comparingInt(o -&gt; o)));</span><br><span class="line">System.out.println(<span class="string">"collectMaxBy:"</span> + collectMaxBy.get());</span><br><span class="line"><span class="comment">// 打印结果</span></span><br><span class="line"><span class="comment">// collectMaxBy:4</span></span><br></pre></td></tr></table></figure>
<p>Collectors averagingInt<br>计算集合的平均年龄</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Double averageAge = persons</span><br><span class="line">    .stream()</span><br><span class="line">    .collect(Collectors.averagingInt(p -&gt; p.age));</span><br><span class="line"></span><br><span class="line">System.out.println(averageAge);     <span class="comment">// 19.0</span></span><br></pre></td></tr></table></figure>
<p>自定义 Collector</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Collector&lt;Person, StringJoiner, String&gt; personNameCollector =</span><br><span class="line">    Collector.of(</span><br><span class="line">        () -&gt; <span class="keyword">new</span> StringJoiner(<span class="string">" | "</span>),          <span class="comment">// supplier</span></span><br><span class="line">        (j, p) -&gt; j.add(p.name.toUpperCase()),  <span class="comment">// accumulator</span></span><br><span class="line">        (j1, j2) -&gt; j1.merge(j2),               <span class="comment">// combiner</span></span><br><span class="line">        StringJoiner::toString);                <span class="comment">// finisher</span></span><br><span class="line"></span><br><span class="line">String names = persons</span><br><span class="line">    .stream()</span><br><span class="line">    .collect(personNameCollector);</span><br><span class="line"></span><br><span class="line">System.out.println(names);  <span class="comment">// MAX | PETER | PAMELA | DAVID</span></span><br></pre></td></tr></table></figure>
</section>
    <!-- Tags START -->
    
    <div class="tags">
      <span>Tags:</span>
      
  <a href="/tags#Java8">
    <span class="tag-code">Java8</span>
  </a>

    </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2019/05/24/Java开源/Github最热门开源项目整理持续更新20190507/">
        <span class="nav-arrow">← </span>
        
          Github 最热门开源项目整理持续更新 20190508
        
      </a>
    
    
      <a class="nav-right" href="/2019/05/24/Java8/java8Stream大数据量List分批处理切割/">
        
          java8 Stream 大数据量 List 分批处理切割
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
    <div class="money-like">
      <div class="reward-btn">
        赏
        <span class="money-code">
          <span class="alipay-code">
            <div class="code-image"></div>
            <b>使用支付宝打赏</b>
          </span>
          <span class="wechat-code">
            <div class="code-image"></div>
            <b>使用微信打赏</b>
          </span>
        </span>
      </div>
      <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
    </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
    <div class="qrcode">
      <canvas id="share-qrcode"></canvas>
      <p class="notice">扫描二维码，分享此文章</p>
    </div>
    
    <!-- 二维码 END -->
    
    <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
  <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#java8-Lambda-Stream-collect-Collectors-常用详细实例"><span class="toc-nav-text">java8 Lambda Stream collect Collectors 常用详细实例</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'https://fengzhaoy.github.io/2019/05/24/Java8/java8LambdaStreamcollectCollectors常用详细实例/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function () {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function () {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="' + src +
          '" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function () {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


<script>
  var qr = new QRious({
    element: document.getElementById('share-qrcode'),
    value: document.location.href
  });
</script>





    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2019
  </p>
</footer>

<script>
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async ("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function () {
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async ("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function () {
    $('figure pre').each(function (i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/js/script.js"></script>
  </body>
</html>